<?php
namespace hangpu8\hpcms\service;

use Exception;

class MenuObserver
{
    /**
     * 查询管理员权限规则列表
     *
     * @param string $user_id
     * @return array
     */
    public function getMenus(string $user_id) : array
    {
        $model = new \hangpu8\hpcms\model\Admin;
        $map['id'] = $user_id;
        $info = $model->with('profile')->where($map)->find();
        if (!$info)
        {
            throw new Exception("找不到管理员信息",404);
        }
        $adminRule = $info->profile->rule;
        $ruleDB = new \hangpu8\hpcms\model\AuthRule;
        $ruleMap = [];
        // 检测管理员是否有权限
        if (!$info->profile->is_system && !$adminRule) {
            throw new Exception("该管理员无任何权限",404);
        }
        // 检测不是系统管理员
        if (!$info->profile->is_system) {
            $ruleMap[] = ['path', 'in', $adminRule];
        }
        $field = 'title,path,method,type,desc,version,icon,pid,show,remote';
        $rules = $ruleDB->where($ruleMap)->order('sort asc,ctime asc')->field($field)->limit(1000)->select()->toArray();

        // 返回数据规则
        return $rules;
    }
}